package org.summerframework.component.security.session.websocket.interceptor;

import org.summerframework.component.security.Constants;
import org.summerframework.component.security.LoginData;
import org.summerframework.component.security.context.RequestContextFactory;
import org.summerframework.core.util.SpringContextUtil;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.*;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.nio.charset.Charset;
import java.security.Principal;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.USER_HEADER;

/**
 * 给webSocket 添加用户
 * {@link LoginData} 继承于 {@link Principal}
 *
 * @param <S> httpSession
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
public final class UserHandshakeInterceptor<S extends Session> extends AbstractHandshakeInterceptor<S> implements ChannelInterceptor, HandshakeInterceptor, ExecutorChannelInterceptor {

    private static final String heartbeat = "heartbeat";

    private final SessionRepository<S> sessionRepository;

    private Set<SimpMessageType> matchingMessageTypes;

    public UserHandshakeInterceptor(SessionRepository<S> sessionRepository) {
        this(sessionRepository, false);
    }

    public UserHandshakeInterceptor(SessionRepository<S> sessionRepository, boolean heartbeatRefreshSession) {
        super(sessionRepository);
        this.sessionRepository = sessionRepository;
        this.matchingMessageTypes = EnumSet.of(SimpMessageType.CONNECT, SimpMessageType.CONNECT_ACK,
                SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE,
                SimpMessageType.UNSUBSCRIBE);

        if (heartbeatRefreshSession) {
            matchingMessageTypes.add(SimpMessageType.HEARTBEAT);
        }
    }

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        SimpMessageHeaderAccessor simpMessageHeaderAccessor = SimpMessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);


        if (simpMessageHeaderAccessor == null || !simpMessageHeaderAccessor.isMutable() || !this.matchingMessageTypes.contains(simpMessageHeaderAccessor.getMessageType())) {
            return message;
        }

        NativeMessageHeaderAccessor nativeMessageHeaderAccessor = NativeMessageHeaderAccessor.getAccessor(message, NativeMessageHeaderAccessor.class);

        //当传head heartbeat为false, 心跳不维护session
        if (nativeMessageHeaderAccessor != null) {
            String key = nativeMessageHeaderAccessor.getFirstNativeHeader(heartbeat);

            if (key != null && !BooleanUtils.toBooleanObject(key.toLowerCase()) && SimpMessageType.HEARTBEAT == simpMessageHeaderAccessor.getMessageType()) {
                return message;
            }
        }

        S session = getSession(message);

        if (session != null) {
            LoginData loginData = session.getAttribute(Constants.SESSION_LOGIN_DATE);
            if (loginData == null) {
                loginData = RequestContextFactory.getLoginData(true);
            }

            //设置用户信息,当用户退出登录后,删除用户信息
            if (loginData.isLogin()) {
                simpMessageHeaderAccessor.setUser(loginData);
            } else {
                simpMessageHeaderAccessor.removeHeader(USER_HEADER);
            }

            //使用@Header(Constants.SESSION_LOGINDATE)获取当前客户端登录信息
            simpMessageHeaderAccessor.setHeader(Constants.SESSION_LOGIN_DATE, loginData);

            if (message instanceof GenericMessage) {
                if (message.getPayload() instanceof String) {
                    if (((String) message.getPayload()).contains("${sessionId}")) {
                        String payload = ((String) message.getPayload()).replace("${sessionId}", session.getId());
                        return new GenericMessage<>(payload.getBytes(Charset.forName("utf-8")), simpMessageHeaderAccessor.getMessageHeaders());
                    }
                } else if (message.getPayload() instanceof byte[]) {
                    String payload = new String((byte[]) message.getPayload()).replace("${sessionId}", session.getId());
                    return new GenericMessage<>(payload.getBytes(Charset.forName("utf-8")), simpMessageHeaderAccessor.getMessageHeaders());
                }
            }
        }

        return message;
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        //设置当前登录的人, 缓存当前连接时的那个人的登录信息
        if (request instanceof ServletServerHttpRequest && response instanceof ServletServerHttpResponse) {
            RequestContextFactory.initRequestContext(((ServletServerHttpRequest) request).getServletRequest(), ((ServletServerHttpResponse) response).getServletResponse(), SpringContextUtil.getApplicationContext().getBean(ServletContext.class));
            HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession(false);
            if (session != null) {
                setSessionId(map, session.getId());
            }
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
